package com.xn.app.muying.activity;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.xn.app.muying.R;
import com.xn.app.muying.bean.BuyTimeBean;
import com.xn.app.muying.sqlite.DBManager;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.BaseActivity;
import com.xn.app.muying.util.MyAlertDialog;
import com.xn.app.muying.wxapi.WXPayEntryActivity;
import com.zhuge.analysis.stat.ZhugeSDK;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;

import okhttp3.Request;

/**
 * 胎心监护
 * Created by Administrator on 2016/11/1.
 */
public class MonitorSelectActivity extends BaseActivity implements View.OnClickListener {
    //返回键
    private ImageView monitorselect_back = null;
    //自主监测
    private Button zizhu_btn = null;
    //实时监测
    private Button shishi_btn = null;
    private Handler handler = new Handler();
    //实时监测可以使用次数
    private int freeCount = -1;
    //购买服务
    private Button buy_service;
    //剩余服务次数
    private TextView servicetime;
    //数据库
    private DBManager db = null;
    //判断监测的类别,true为自助监测，flase为实时监测
    public static Boolean mSign = true;
    //加载框
    MyAlertDialog dialog = null;
    //类对象
    public static MonitorSelectActivity monitorSelectActivity = null;
    //购买实时监测数据集合
    ArrayList<BuyTimeBean> list;
    //营养中心
    private TextView shop_textview=null;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_monitorselect);
        monitorSelectActivity = this;
        db = new DBManager(MonitorSelectActivity.this);
        monitorselect_back = (ImageView) findViewById(R.id.monitorselect_back);
        zizhu_btn = (Button) findViewById(R.id.activity_monitorselect_zizhu);
        shishi_btn = (Button) findViewById(R.id.activity_monitorselect_shishi);
        shishi_btn.setClickable(false);
        ImageButton history_record = (ImageButton) findViewById(R.id.history_record);
        buy_service = (Button) findViewById(R.id.activity_monitorselect_buy);
        servicetime = (TextView) findViewById(R.id.activity_monitorselect_servicetime);
        shop_textview = (TextView)findViewById(R.id.shop_textview);
        zizhu_btn.setOnClickListener(this);
        shishi_btn.setOnClickListener(this);
        buy_service.setOnClickListener(this);
        monitorselect_back.setOnClickListener(this);
        shop_textview.setOnClickListener(this);
        history_record.setOnClickListener(this);
        try {
            ZhugeSDK.getInstance().track(getApplicationContext(), "胎心监护");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    AlertDialog dialog1;
    @Override
    public void onClick(View view) {
        Intent intent = new Intent();
        switch (view.getId()) {
            //返回键
            case R.id.monitorselect_back:
                finish();
                break;
            //查看历史记录
            case R.id.history_record:
                //  HistoryRecordActivity   暂行性方案
                intent.setClass(MonitorSelectActivity.this, TaiXinLieBiaoActivity.class);
                startActivity(intent);
                break;
            //实时监测
            case R.id.activity_monitorselect_shishi:
                if (db.select("identityId") != null && !db.select("identityId").equals("") && !db.select("identityId").equals("null")) {
                    if (freeCount != 0 && freeCount > 0) {
                        if (db.select("pregnancyStatus").equals("1")) {
                            mSign = false;
                            intent.setClass(MonitorSelectActivity.this, LianJieActivity.class);
                            startActivity(intent);
                        } else {
                            showPregnancyStatusDialog();
                        }
                    } else {
                        Toast.makeText(MonitorSelectActivity.this, "您的服务次数已经用完，赶紧去购买吧"
                                , Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(MonitorSelectActivity.this, "您需要先验证身份", Toast.LENGTH_SHORT).show();
                    //完善个人信息
                    intent.setClass(MonitorSelectActivity.this, PersonalActivity.class);
                    intent.putExtra("type", "1");
                    startActivity(intent);
                }
                break;
            //自主监测
            case R.id.activity_monitorselect_zizhu:
                if (db.select("pregnancyStatus").equals("1")) {
                    mSign = true;
                    intent.setClass(MonitorSelectActivity.this, LianJieActivity.class);
                    startActivity(intent);
                } else {
                    showPregnancyStatusDialog();
                }
                break;
            //购买服务次数
            case R.id.activity_monitorselect_buy:
                //获取服务项
                dialog1 = new MyAlertDialog().ShowDialog(MonitorSelectActivity.this, R.layout.dialog_loading);
                dialog1.setCancelable(true);
                getServiceData();
                //intent.setClass(MonitorSelectActivity.this, BuyServiceActivity.class);
                //startActivity(intent);
                break;
            //营养中心
            case R.id.shop_textview:
                intent.putExtra("title", "营养中心");
                intent.putExtra("url", APIMethod.WeiDianTaiXin);
                intent.setClass(MonitorSelectActivity.this, WebActivity.class);
                startActivity(intent);
                break;
        }
    }

    /**
     * 胎心监测怀孕状态判断
     */
    private void showPregnancyStatusDialog() {
        try {
            //加载弹出框
            final MyAlertDialog dialog = new MyAlertDialog();
            dialog.PregnancyStatus_Dialog(MonitorSelectActivity.this, R.layout.pregnancystatus_dialog);
            //设置取消按钮
            TextView getCancel_text = dialog.getCancel_text();
            getCancel_text.setText("取消");
            getCancel_text.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    dialog.dismissOut();
                }
            });
            //设置确认按钮
            TextView getConfirm_text = dialog.getConfirm_text();
            getConfirm_text.setText("设置");
            getConfirm_text.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    dialog.dismissOut();
                    Intent mIntent = new Intent();
                    mIntent.putExtra("PAGE_INTENT", "MineFragment");
                    mIntent.setClass(MonitorSelectActivity.this, YunQiXuanZeActivity.class);
                    startActivity(mIntent);
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //获取服务剩余次数数据
    public void getData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Request request = new Request.Builder().url(APIMethod.Usufruct(db.select("antenatalCareHospitalId"))).addHeader("Authorization", db.select("token_type") + " " + db.select("access_token")).get().build();
                    okhttp3.Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    String bodys = response.body().string();
                    onJsonData(bodys);
                } catch (IOException e) {
                    e.printStackTrace();

                }
            }


        }).start();
    }

    //解析服务剩余次数
    private void onJsonData(String bodys) {
        try {
            JSONObject jsonObject = new JSONObject(bodys);
            freeCount = jsonObject.optInt("freeCount");
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    servicetime.setText("医院服务剩余次数: " + freeCount + "次");
                    servicetime.setVisibility(TextView.VISIBLE);
                    shishi_btn.setClickable(true);
                }
            });

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    /**
     * 显示套餐支付成功弹框
     */
    private void showMonitorDialog() {
        try {
            //加载弹出框
            dialog = new MyAlertDialog();
            dialog.Monitor_Dialog(MonitorSelectActivity.this, R.layout.monitor_dialog);
            //设置内容
            TextView data = dialog.getData();
            data.setText(Html.fromHtml(getIntent().getStringExtra("success")));
            //设置取消按钮
            TextView getConfirm_text = dialog.getConfirm_text();
            getConfirm_text.setText("我知道了");
            getConfirm_text.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    dialog.dismissOut();
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void getServiceData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Request request = new Request.Builder().url(APIMethod.Buy_Time(1)).addHeader("Authorization", db.select("token_type") + " " + db.select("access_token")).get().build();
                    okhttp3.Response response = MuYingApplication.mOkHttpClient.newCall(request).execute();
                    String bodys = response.body().string();
                    onData(bodys);
                } catch (IOException e) {
                    e.printStackTrace();

                }
            }


        }).start();
    }

    //获取购买实时监测次数数据
    public void onData(String data) {

        try {
            JSONObject jsonObject = new JSONObject(data);
            JSONArray items = jsonObject.getJSONArray("items");
            list = new ArrayList<>();
            for (int i = 0; i < items.length(); i++) {
                JSONObject object = items.getJSONObject(i);
                String name = object.optString("name");
                String serviceTypeId = object.optString("serviceTypeId");
                String serviceType = object.optString("serviceTypeName");
                String serviceCount = object.optString("serviceCount");
                String price = object.optString("price");
                String compnayId = object.optString("compnayId");
                String companyName = object.optString("companyName");
                String description = object.optString("description");
                String originalPrice = object.optString("originalPrice");
                String paySuccessDescription = object.optString("paySuccessDescription");
                String id = object.optString("id");
                BuyTimeBean buyTimeBean = new BuyTimeBean();
                buyTimeBean.setName(name);
                buyTimeBean.setServiceTypeId(serviceTypeId);
                buyTimeBean.setServiceType(serviceType);
                buyTimeBean.setServiceCount(serviceCount);
                buyTimeBean.setPrice(price);
                buyTimeBean.setDescription(description);
                buyTimeBean.setOriginalPrice(originalPrice);
                buyTimeBean.setPaySuccessDescription(paySuccessDescription);
                buyTimeBean.setCompnayId(compnayId);
                buyTimeBean.setCompanyName(companyName);
                buyTimeBean.setId(id);
                //开发权限
                if (!id.equals("17")) {
                    list.add(buyTimeBean);
                }
            }
            dialog1.dismiss();
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Intent intent = new Intent();
                    intent.putExtra("companyName", list.get(0).getCompanyName());
                    intent.putExtra("name", list.get(0).getName());
                    intent.putExtra("serviceType", list.get(0).getServiceType());
                    intent.putExtra("serviceCount", list.get(0).getServiceCount());
                    intent.putExtra("price", list.get(0).getPrice());
                    intent.putExtra("id", list.get(0).getId());
                    intent.putExtra("description", list.get(0).getDescription());
                    intent.putExtra("sign", "MonitorSelectActivity");
                    intent.setClass(MonitorSelectActivity.this, ReadyPayActivity.class);
                    startActivity(intent);
                }
            });

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    @Override
    protected void onResume() {
        super.onResume();
        getData();
        if (getIntent().getStringExtra("success") != null && !getIntent().getStringExtra("success").equals("") && !getIntent().getStringExtra("success").equals("null") && WXPayEntryActivity.i == 0) {
            showMonitorDialog();
            WXPayEntryActivity.i = 1;
        }
    }

}
